package site.qjdb.util;

import io.jsonwebtoken.*;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Map;

public class JWTUtils {

	/**
	 * 	发行者
	 */
	private static final String SUBJECT = "QYGK";

	/**
	 * 	过期时间，默认30天
	 */
	private static final  long EXPIRED = 2592000000L;


	/**
	 * 	密钥
	 */
	private static final String SECRET = "^ks!hx@y#zx%z&l*7777$";

	/**
	 * 默认key
	 */
	private static final String DEFAULT_KEY = "default";

	/**
	 * 生成token
	 *
	 */
	public static String token(String key, Object obj) {
		return generateToken(key, obj);
	}

	/**
	 * 生成token
	 *
	 */
	public static String token(Object obj) {
		return generateToken(DEFAULT_KEY, obj);
	}

	/**
	 * 校验token
	 * 	过期返回null
	 * 	否则返回clazz实例
	 */
	public static Object checkToken(String token, String key, Class<?> clazz) {
		if(CommonUtils.isEmpty(token)) {
			return null;
		}
		Claims c = check(token);
		return mapToBean(c, key, clazz);
	}

	/**
	 * 校验token
	 */
	public static Object checkToken(String token,  Class<?> clazz) {
		return checkToken(token, DEFAULT_KEY, clazz);
	}

	/**
	 * 	生成 jwt token
	 *
	 */
	private static String generateToken(String key, Object val) {
		long start = System.currentTimeMillis();
		JwtBuilder jwtBuilder = Jwts.builder();
		// 荷载信息
		jwtBuilder.claim(key, val);
		String compact = jwtBuilder.setSubject(SUBJECT)
				.setIssuedAt(new Date())
				.setExpiration(new Date(System.currentTimeMillis() + EXPIRED))
				.signWith(SignatureAlgorithm.HS256, SECRET)
				.compressWith(CompressionCodecs.DEFLATE) // 对载荷进行压缩
				.compact();// 压缩
		long end = System.currentTimeMillis();
		System.out.println(end - start);
		return compact;
	}

	/**
	 * 	校验 token
	 *
	 * @param token
	 * @return
	 */
	private static Claims check(String token) {
		try {
			final Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
			return claims;
		} catch (Exception e) {
			System.out.println(1);
		}
		return null;
	}

	private static Object mapToBean(Claims c, String key, Class<?> clazz) {
		try {
			Map<String, Object> map = c.get(key, Map.class);
			Object obj = clazz.newInstance();
			if (map != null && !map.isEmpty() && map.size() > 0) {
				for (Map.Entry<String, Object> entry : map.entrySet()) {
					String propertyName = entry.getKey(); // 属性名
					Object value = entry.getValue(); // 属性值
					Field field = getClassField(clazz, propertyName); // 获取和map的key匹配的属性名称
					if (field == null || value == null) {
						continue;
					}
					String setMethodName = "set" + propertyName.substring(0, 1).toUpperCase()
							+ propertyName.substring(1);
					Class<?> fieldTypeClass = field.getType();
					value = convertValType(value, fieldTypeClass);
					try {
						clazz.getMethod(setMethodName, field.getType()).invoke(obj, value);
					} catch (Exception e) {
					}
				}
			}
			return obj;
		} catch (Exception e) {
		}
		return null;
	}

	private static Field getClassField(Class<?> clazz, String fieldName) {
		if (Object.class.getName().equals(clazz.getName())) {
			return null;
		}
		Field[] declaredFields = clazz.getDeclaredFields();
		for (Field field : declaredFields) {
			if (field.getName().equals(fieldName)) {
				return field;
			}
		}
		Class<?> superClass = clazz.getSuperclass(); // 如果该类还有父类，将父类对象中的字段也取出
		if (superClass != null) { // 递归获取
			return getClassField(superClass, fieldName);
		}
		return null;
	}

	private static Object convertValType(Object value, Class<?> fieldTypeClass) {
		if (value == null) {
			return null;
		}
		Object retVal = null;
		if (Long.class.getName().equals(fieldTypeClass.getName())
				|| long.class.getName().equals(fieldTypeClass.getName())) {
			retVal = Long.parseLong(value.toString());
		} else if (Integer.class.getName().equals(fieldTypeClass.getName())
				|| int.class.getName().equals(fieldTypeClass.getName())) {
			retVal = Integer.parseInt(value.toString());
		} else if (Float.class.getName().equals(fieldTypeClass.getName())
				|| float.class.getName().equals(fieldTypeClass.getName())) {
			retVal = Float.parseFloat(value.toString());
		} else if (Double.class.getName().equals(fieldTypeClass.getName())
				|| double.class.getName().equals(fieldTypeClass.getName())) {
			retVal = Double.parseDouble(value.toString());
		} else if (Date.class.getName().equals(fieldTypeClass.getName())) {
			retVal = (Date) retVal;
		} else {
			retVal = value;
		}
		return retVal;
	}

}
